 package com.ficoxml.xmlparser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class OutputdataXmlParser extends GenericUDTF {


	 private PrimitiveObjectInspector stringOI = null;
     @Override
     public StructObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
     	System.out.println("initialize初始化");
     	// 异常检测
         if (objectInspectors.length != 3) {
             throw new UDFArgumentException("NameParserGenericUDTF() takes exactly one argument");
         }

         if(objectInspectors[0].getCategory()!=ObjectInspector.Category.PRIMITIVE&&((PrimitiveObjectInspector) objectInspectors[0]).getPrimitiveCategory() != PrimitiveObjectInspector.PrimitiveCategory.STRING) {
             throw new UDFArgumentException("NameParserGenericUDTF() takes a string as a parameter");
         }
     	
         //输入
         stringOI = (PrimitiveObjectInspector) objectInspectors[0];
//         System.out.println("stringOI"+stringOI.toString());
         // 输出
         List<String> fieldNames = new ArrayList<String>(23);
         List<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>(23);
         
         // 输出列名
//         outputField(fieldNames,fieldOIs);
         
         String[] arr = { "XM1GYSJHBTXMSQCS", "XM1GYSJHBTSFZSQCS", "XM1GYSFZHBTSJHSQCS", "idCardByPhone1D",
                 "nameByIdCard1D", "IdCardByPhone7D", "nameByIdCard7D", "XM15TNTYSJHSQCS", "XM15TNTYSFZSQCS",
                 "idCardByPhone30D", "nameByIdCard30D", "idCardByPhone3M", "nameByIdCard3M", "idCardByPhone6M",
                 "nameByIdCard6M", "idCardByPhone12M", "nameByIdCard12M", "lastRejectDays", "idCardByIMEI",
                 "phoneByIMEI", "imeiByIdCard", "imeiByPhone" };
         System.out.println("arr"+arr[1]);
         fieldNames.add("appid");
         fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
         for (int i = 0; i < arr.length; i++) {
         	fieldNames.add(arr[i]);
         	fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
			}
         System.out.println("初始化结束");
         
         // 返回分别为列名 和 列类型
         return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
     }

     @Override
     public void process(Object[] objects) throws HiveException {
     	System.out.println("执行process");
//     	final String feature = stringOI.getPrimitiveJavaObject(objects[0]).toString();
//     	System.out.println("feature"+feature.toString());
//     	System.out.println("stringOI"+stringOI.toString());
     	if (objects.length < 3) {
     		System.out.println("不符合数据格式!");
			forward(objects);
			return;
		}
     	String xml=(String) objects[0];
     	System.out.println("xml="+xml.toString());
     	String[] arr=(String[]) objects[1];
     	String tablename = (String) objects[2];
     	System.out.println("tablename="+tablename);
         String[] a=geneRow(xml,arr,tablename);
         System.out.println("结果为+"+Arrays.toString(a));
//         forward(a);

     }

     public String[] geneRow(String xml,String [] arr,String tablename){
        
         String[] String=readStringXmlOut(xml,tablename,arr);
         return String;
     }
     public  String[] readStringXmlOut(String data, String tablename, String[] arr) {

         Document doc = null;
         // 将字符串转为XML
         try {
             doc = DocumentHelper.parseText(data);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         // 获取根节点
         Element rootElt = doc.getRootElement(); 
         Iterator iterss = rootElt.elementIterator(tablename);
         String ret[]=new String[arr.length+1];
         System.out.println("arr.length"+arr.length);
         while (iterss.hasNext()) {
             ret[0]=rootElt.attributeValue("AppId");
             
             Element recordEless = (Element) iterss.next();
             Iterator iterss1 = recordEless.elementIterator("ScoredCharacteristic");
             System.out.println("BaselineScore="+recordEless.attributeValue("BaselineScore"));
            System.out.println("FinalScore="+recordEless.attributeValue("FinalScore"));
            System.out.println("ScoreModelName="+recordEless.attributeValue("ScoreModelName"));
            
            
            
            //            	 while (iterss1.hasNext()) {
//            		 
//            		 System.out.println("BaselineScore="+recordEless.attributeValue("BaselineScore"));
//		 
//             }
//             for (int i = 0; i < arr.length; i++) {
//                 if(recordEless.attributeValue(arr[i])==""){
//                     ret[i+1]="";
//                 }else {
//                     ret[i+1]=recordEless.attributeValue(arr[i]);
//                 }
//             }
             
         }

         return ret;
     }

     @Override
     public void close() throws HiveException {

     }


    public static void main(String[] args) throws HiveException {
    	OutputdataXmlParser OutputdataXmlParser=new OutputdataXmlParser();
        String xml="<Application AppId=\"jksidhaish8796987sadfasdfjd100842\" SourceCode=\"newupBank\">"
        		+ "<ScoreModelReturnInfo FinalScore=\"462.0\" ScoreModelName=\"申请评分模型1\">		"
        		+ "<ScoredCharacteristic BaselineScore=\"0.2\" BinLabel=\"男1\" />	<ScoredCharacteristic "
        		+ "BaselineScore=\"0.0\" BinLabel=\"男\" />		"
        		+ "</ScoreModelReturnInfo>	<ReturnInfoVariable workingYears=\"30.0\"/>	"
        		+ "<ScoreModelReturnInfo FinalScore=\"461.0\" ScoreModelName=\"申请评分模型\">		"
        		+ "<ScoredCharacteristic BaselineScore=\"0.1\" BinLabel=\"女\" /></ScoreModelReturnInfo></Application>";
        System.out.println(xml);
        String[] arr = { "BaselineScore", "BinLabel","FinalScore","ScoreModelName"};
        String tablename = "ScoreModelReturnInfo";
        	 Object[] obj=new Object[3];
        	 obj[0]=xml;
        	 obj[1]=arr;
        	 obj[2]=tablename;
        	 OutputdataXmlParser.process(obj);
    }
}
